package net.expectx.pay.merchant.controller.product;

import com.alibaba.fastjson.JSONObject;
import io.swagger.annotations.ApiOperation;
import net.expectx.common.single.base.BaseConstants;
import net.expectx.pay.dao.bean.*;
import net.expectx.pay.merchant.common.AdminConstants;
import net.expectx.pay.rpc.api.MerchantApplicationService;
import net.expectx.pay.rpc.api.PaymentChannelService;
import net.expectx.pay.rpc.api.ProductOrderHeaderService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author hxs
 */
@Controller
@RequestMapping(value = "/manager/product/orderHeader")
public class ProductOrderHeaderController {
    private final static String PAY_SUCCESS ="1";

    @Autowired
    private ProductOrderHeaderService productOrderHeaderService;

    @Autowired
    private PaymentChannelService paymentChannelService;
    @Autowired
    private MerchantApplicationService merchantApplicationService;
    @ApiOperation(value = "订单主页")
    @RequestMapping(value = "/index", method = RequestMethod.GET)
    public String index( ModelMap modelMap,String orderType,String todayOrder) {
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MerchantUser merchantUser = (MerchantUser) session.getAttribute("merchantUser");
        String merchantNo = null;
        if (null != merchantUser) {
            merchantNo = merchantUser.getMerchantNo();
        }
        if (StringUtils.isNotBlank(orderType)) {
            modelMap.put("orderType", orderType);
        }
        if (StringUtils.isNotBlank(todayOrder)) {
            modelMap.put("todayOrder", todayOrder);
        }

        MerchantApplicationExample merchantApplicationExample = new MerchantApplicationExample();
        MerchantApplicationExample.Criteria criteria1 = merchantApplicationExample.createCriteria();
        criteria1.andIsDeletedEqualTo(BaseConstants.NO);
        criteria1.andMerchantNoEqualTo(merchantNo);
        List<MerchantApplication> merchantApplications = merchantApplicationService.selectByExample(merchantApplicationExample
        );
        modelMap.put("merchantApplications", merchantApplications);
        List<String> ChannelList = new ArrayList();
        for (MerchantApplication merchantApplication : merchantApplications) {
            String[] split = merchantApplication.getPaymentChannel().split(",");
            List<String> strings = Arrays.asList(split);
            ChannelList.removeAll(strings);
            ChannelList.addAll(strings);
        }
        PaymentChannelExample paymentChannelExample = new PaymentChannelExample();
        PaymentChannelExample.Criteria  criteria= paymentChannelExample.createCriteria();
        criteria.andIsDeletedEqualTo(BaseConstants.NO);
        if (!ChannelList.isEmpty()){
            List<Long> list = new ArrayList<>();
            for (String s : ChannelList) {
                Long aLong = Long.valueOf(s);
                list.add(aLong);
            }
            criteria1.andIdIn(list);
        }
        List<PaymentChannel> paymentChannels = paymentChannelService.selectByExample(paymentChannelExample);
        modelMap.put("paymentChannels", paymentChannels);


//        ProductOrderHeaderExample productOrderHeaderExample = new ProductOrderHeaderExample();
//        ProductOrderHeaderExample.Criteria criteria = productOrderHeaderExample.createCriteria();
//        List<ProductOrderHeader> productOrderHeaders = productOrderHeaderService.selectByExample(productOrderHeaderExample);
//        BigDecimal sum = new BigDecimal("0");
//        BigDecimal serviceFee = new BigDecimal("0");
//
//        for (ProductOrderHeader productOrderHeader : productOrderHeaders) {
//            sum = sum.add(productOrderHeader.getGrandTotal());
//        }
//        for (ProductOrderHeader productOrderHeader : productOrderHeaders) {
//            serviceFee = serviceFee.add(productOrderHeader.getServiceFee());
//        }
//        modelMap.put("sum", sum);
//        modelMap.put("serviceFee", serviceFee);
//        modelMap.put("total", productOrderHeaders.size());
        return "product/orderHeader/index";
    }

    @RequestMapping(value = "/page", method = RequestMethod.GET)
    @ResponseBody
    public Object list(
            @RequestParam(required = false, defaultValue = "1", value = "page") int page,
            @RequestParam(required = false, defaultValue = "10", value = "limit") int limit,
            HttpServletRequest request)throws ParseException {

        ProductOrderHeaderExample productOrderHeaderExample = new ProductOrderHeaderExample();
        ProductOrderHeaderExample.Criteria criteria = productOrderHeaderExample.createCriteria();
        Subject subject = SecurityUtils.getSubject();
        Session session = subject.getSession();
        MerchantUser merchantUser = (MerchantUser) session.getAttribute("merchantUser");
        String merchantNo = null;
        if (null != merchantUser) {
            merchantNo = merchantUser.getMerchantNo();
        }
        String startTime1 = request.getParameter("startTime1");
        String startTime2 = request.getParameter("startTime2");
        String endTime1 = request.getParameter("endTime1");
        String endTime2 = request.getParameter("endTime2");
        String orderId = request.getParameter("orderId");
        String tradeNo = request.getParameter("tradeNo");
        String orderType = request.getParameter("orderType");
        String orderType1 = request.getParameter("orderType1");
        if(orderType1!=null){
            orderType = orderType1;
        }
        String payStatus = request.getParameter("payStatus");
        String merchantOrderId = request.getParameter("merchantOrderId");
        String grandTotal = request.getParameter("grandTotal");
        String paymentChannel = request.getParameter("paymentChannel");
        String merchantApplication = request.getParameter("merchantApplication");
        String todayOrder = request.getParameter("todayOrder");
        productOrderHeaderExample.setPageIndex(page);
        productOrderHeaderExample.setPageSize(limit);

        productOrderHeaderExample.setOrderByClause("gmt_modified desc");
        Map<String,Object> map = productOrderHeaderService.findPageByStrWhere( page,  limit, merchantNo, tradeNo,  orderId, endTime2, endTime1,  startTime2, startTime1, grandTotal,  merchantOrderId,  payStatus,  orderType, merchantApplication,
                 paymentChannel, todayOrder, null);
        long total = productOrderHeaderService.countByExample(productOrderHeaderExample);
        List<ProductOrderHeader> productOrderHeaders = (List<ProductOrderHeader>) map.get("productOrderHeaders");
        BigDecimal settlementTotal= new BigDecimal(0);
        for (ProductOrderHeader productOrderHeader : productOrderHeaders) {
            if (PAY_SUCCESS.equals(productOrderHeader.getOrderStatus())){
                settlementTotal=settlementTotal.add(productOrderHeader.getGrandTotal());
            }
        }
        Map<String, Object> result = new HashMap<>(16);
        request.setAttribute("serviceFee", map.get("serviceFee"));
        request.setAttribute("sum",map.get("sum"));
        result.put("code", AdminConstants.LAYUI_DATA_OK);
        result.put("count", map.get("total"));
        result.put("serviceFee", map.get("serviceFee"));
        result.put("sumMoney", map.get("sum"));
        result.put("settlementTotal", settlementTotal);
        result.put("msg", "");
        result.put("data", map.get("productOrderHeaders"));
        return result;
    }

    @ApiOperation(value = "订单详情")
    @RequestMapping(value = "/orderDetails/{id}", method = RequestMethod.GET)
    public String orderDetails(HttpServletRequest request, ModelMap modelMap,@PathVariable("id") String id) {
        ProductOrderHeaderExample productOrderHeaderExample = new ProductOrderHeaderExample();
        ProductOrderHeaderExample.Criteria criteria = productOrderHeaderExample.createCriteria();
        criteria.andIsDeletedEqualTo(AdminConstants.NO);
        criteria.andOrderIdEqualTo(id);
        ProductOrderHeader productOrderHeader = productOrderHeaderService.selectByExample(productOrderHeaderExample).get(0);
        modelMap.put("procudtOrderHeader", productOrderHeader);
        return "product/orderHeader/orderDetails";
    }

    private static Long getLongTime(String time)throws ParseException{
        DateFormat bf = new SimpleDateFormat("yyyy-MM-dd");//多态
        return bf.parse(time).getTime();
    }
public static void main(String[] args)  {

}
}
